import React, { useState } from "react";
import { Form, Input, Button, Card, message } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { AdminControllerService } from "../api";

interface LoginFormValues {
  username: string;
  password: string;
}

const Login: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const onFinish = async (values: LoginFormValues) => {
    setLoading(true);
    try {
      console.log("🚀 开始登录请求...", values);
      const response = await AdminControllerService.loginUsingPost(values);
      console.log("✅ 登录API响应:", response);
    } catch (error: any) {
      console.error("❌ 登录失败:", error);

      const errorMessage =
        error.response?.data?.message ||
        error.message ||
        "登录失败，请检查网络连接";

      message.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div
      style={{
        height: "100vh",
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
      }}
    >
      <Card
        title="后台管理系统"
        style={{ width: 400, boxShadow: "0 4px 12px rgba(0,0,0,0.15)" }}
        headStyle={{
          textAlign: "center",
          fontSize: "20px",
          fontWeight: "bold",
        }}
      >
        <Form
          form={form}
          name="login"
          onFinish={onFinish}
          autoComplete="off"
          size="large"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: "请输入用户名!" }]}
          >
            <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: "请输入密码!" }]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="密码" />
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              style={{ width: "100%" }}
            >
              {loading ? "登录中..." : "登录"}
            </Button>
          </Form.Item>
        </Form>

        <div style={{ textAlign: "center", color: "#666", fontSize: "12px" }}>
          <div>默认账号：admin，密码：admin</div>
          <div style={{ marginTop: "4px" }}>Token将从响应头自动获取</div>
        </div>
      </Card>
    </div>
  );
};

export default Login;
